package service;
import entity.Product;
import mapper.ProductMapper;
import util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ProductServiceImpl implements ProductService{

    //1. 查询所有的产品信息
    @Override
    public List<Product> findAll() {
        //1. 获取sqlSession
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        //2. 获取userMapper
        ProductMapper proMapper = sqlSession.getMapper(ProductMapper.class);
        //3. mapper接口中的方法
        List<Product> proList = proMapper.findAll();
        //4. 关闭资源
        sqlSession.close();
        return proList;
    }
    //2. 根据产品的名称进行模糊查询
    @Override
    public List<Product> findByLikeUsername(String name) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        ProductMapper proMapper = sqlSession.getMapper(ProductMapper.class);
        List<Product> proList = proMapper.findByLikeUsername(name);
        sqlSession.close();
        return proList;
    }
    //3. 根据产品的类型的id进行精确查询
    @Override
    public Product getById(Integer id) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        ProductMapper proMapper = sqlSession.getMapper(ProductMapper.class);
        Product pro=proMapper.getById(id);
        sqlSession.close();
        return pro;
    }
    //4. 根据产品的id进行删除
    @Override
    public int delById(Integer id) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        ProductMapper proMapper = sqlSession.getMapper(ProductMapper.class);
        int num=proMapper.delById(id);
        sqlSession.commit();
        sqlSession.close();
        return num;
    }
    //5. 保存一个产品
    @Override
    public int save(Product pro) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        ProductMapper proMapper = sqlSession.getMapper(ProductMapper.class);
        int num=proMapper.save(pro);
        sqlSession.commit();
        sqlSession.close();

        return num;
    }
    //6. 根据产品的id进行更新
    @Override
    public int update(Product pro) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        ProductMapper proMapper = sqlSession.getMapper(ProductMapper.class);
        int num=proMapper.update(pro);
        sqlSession.commit();
        sqlSession.close();
        return num;
    }
}
